import { createCaches } from 'az-caches'

class AzPermission {
  constructor(permissions, adminPermission) {
    this.permissions = createCaches(permissions)
    typeof adminPermission !== 'undefined' && (this.isAdmin = this.permissions.has(adminPermission))
  }

  has(value) {
    if (this.isAdmin) return this.isAdmin
    value === Object(value) && (value[Symbol.isConcatSpreadable] = true)
    const flags = [].concat(value)
    return flags.some((flag) => this.permissions.has(flag))
  }

  hasNot(value) {
    return !this.has(value)
  }
}

export function createPermissions(permissions, adminPermission) {
  return new AzPermission(permissions, adminPermission)
}
